/*
	

*/

#include "iot_server.h"

pthread_mutex_t coord_mutex;//创建互斥锁
pthread_t tid_recv_mob_thread;
pthread_t tid_recv_coord_thread;

void start_tcp_server(void)
{
	
	int ret = -1;
	int newfd ;
	//recv_coord_fun();
	//1.买电话
	int fd = socket(AF_INET, SOCK_STREAM, 0);
	if (fd == -1) {
		perror("socket");
	}
	//重用端口
	int on = 1;
	setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

	//2.绑卡 ip+port
	struct sockaddr_in server; //设置服务端ip+port
	server.sin_family = AF_INET;
	server.sin_port = htons(12345);
	server.sin_addr.s_addr = inet_addr("192.168.104.221");
	ret = bind(fd, (struct sockaddr *)&server, sizeof(server));
	if (ret == -1) {
		perror("bind");
	}

	//3.监听

	listen(fd, 5);
	//4.接听
	struct sockaddr_in client; //接收客户端ip+port对象
	socklen_t len = sizeof(client);

	printf("tcp server start... \n");
	system("netstat -na | grep 12345"); //查看tcp连接状态
	// 接收客户请求并建立和服务器端连接 并发服务器
	while (1) {
		newfd = accept(fd, (struct sockaddr *)&client, &len); //阻塞函数
		//没有客户端请求就让进程暂停,当有请求成功,建立连接返回
		if (newfd == -1) {
			perror("accept");
		}
		printf("client ip=%s\n", inet_ntoa(client.sin_addr));
		printf("client port=%d\n", ntohs(client.sin_port));
		printf("客户端 fd=%d 上线!\n", newfd);
		
		//pthread_t tid;
		//pthread_create(&tid, NULL, send_mob_fun, &newfd);

		//5.通信
		//创建接收线程
		
		pthread_create(&tid_recv_mob_thread, NULL, recv_mob_thread, &newfd);
	}
	//6.挂电话
	sleep(10);
	close(fd);


}

//当ctrl+c 或 ctrl+\  给进程发信号,内核就调用信号处理函数main_exit
// 释放项目的资源  2个线程,锁对象

void main_exit(int signo)
{
	pthread_cancel(tid_recv_mob_thread);
	pthread_cancel(tid_recv_coord_thread);
	pthread_mutex_destroy(&coord_mutex);
	printf("main thread quit, release all resource\n");
	exit(0);
}


int main(void)
{
	
	//注册信号处理函数
	signal(SIGINT, main_exit);
	signal(SIGQUIT, main_exit);


	//初始化
	pthread_mutex_init(&coord_mutex, NULL);
	pthread_create(&tid_recv_coord_thread, NULL, recv_coord_thread, NULL);
	start_tcp_server();
	

	return 0;
}
